function handleAuthError() {
    addMessage('系统提示：请先登录后再使用', 'system');
    window.location.href = '/login';
}

async function sendMessage() {
    const message = messageInput.value.trim();
    if (!message) return;

    if (messageCount >= MESSAGE_LIMIT) {
        showRechargeModal();
        return;
    }

    const now = Date.now();
    if (isWaiting || (now - lastMessageTime < THROTTLE_DELAY)) {
        updateStatus('请稍等片刻再发送消息', true);
        return;
    }

    setLoading(true);
    isWaiting = true;
    lastMessageTime = now;
    
    addMessage(message, 'user');
    messageInput.value = '';

    let currentMessageDiv = null;
    let currentContent = '';

    try {
        const response = await fetch('/api/chat/stream', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'text/event-stream',
            },
            body: `message=${encodeURIComponent(message)}`
        });

        if (response.status === 401) {
            handleAuthError();
            return;
        }

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const {value, done} = await reader.read();
            if (done) {
                setLoading(false);
                isWaiting = false;
                if (currentMessageDiv) {
                    currentMessageDiv.classList.remove('typing');
                }
                break;
            }

            const chunk = decoder.decode(value, {stream: true});
            const lines = chunk.split('\n');

            for (const line of lines) {
                if (!line.trim() || !line.startsWith('data: ')) continue;

                const data = line.slice(5).trim();
                if (data === '[DONE]') {
                    setLoading(false);
                    isWaiting = false;
                    if (currentMessageDiv) {
                        currentMessageDiv.classList.remove('typing');
                    }
                    continue;
                }

                try {
                    const jsonData = JSON.parse(data);
                    
                    if (jsonData.code === 401) {
                        handleAuthError();
                        return;
                    }
                    
                    if (jsonData.code === 500) {
                        addMessage('系统提示：' + jsonData.msg, 'system');
                        updateStatus(jsonData.msg, true);
                        break;
                    }

                    if (jsonData.code === 200 && jsonData.choices && jsonData.choices.length > 0) {
                        const choice = jsonData.choices[0];
                        const content = choice.delta?.content || '';
                        
                        if (content || choice.finish_reason === 'stop') {
                            if (!currentMessageDiv) {
                                currentMessageDiv = document.createElement('div');
                                currentMessageDiv.className = 'message ai-message typing';
                                chatContainer.appendChild(currentMessageDiv);
                            }

                            if (content.startsWith('系统提示：')) {
                                currentMessageDiv.className = 'message system-message';
                                updateStatus(content, true);
                            }

                            if (content) {
                                currentContent += content;
                                currentMessageDiv.innerHTML = formatMessage(currentContent);
                                chatContainer.scrollTop = chatContainer.scrollHeight;
                            }
                        }
                    }
                } catch (e) {
                    console.error('Error parsing JSON:', e, data);
                    if (!currentMessageDiv) {
                        addMessage('系统提示：解析响应失败', 'system');
                        updateStatus('解析响应失败', true);
                    }
                }
            }
        }
    } catch (error) {
        console.error('Error:', error);
        addMessage('系统提示：发送消息失败，请重试', 'system');
        updateStatus('发送消息失败，请重试', true);
    } finally {
        setLoading(false);
        isWaiting = false;
    }
}

async function isUserLoggedIn() {
    try {
        const response = await fetch('/api/auth/check');
        const isLoggedIn = await response.json();
        return isLoggedIn;
    } catch (error) {
        console.error('检查登录状态失败:', error);
        return false;
    }
} 